package org.freespace.controller;


import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.freespace.Constant;
import org.freespace.model.JmxArguments;
import org.freespace.model.JmxPlugin;
import org.freespace.model.JmxScript;
import org.freespace.service.IJmxScriptService;
import org.freespace.utils.response.CommonResult;
import org.freespace.vo.JmxScriptVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * <p>
 * jmx脚本文件表 前端控制器
 * </p>
 *
 * @author liuqi
 * @since 2023-04-27
 */
@Slf4j
@RestController
@RequestMapping("/jmx-script")
public class JmxScriptController {

    @Autowired
    IJmxScriptService scriptService;

    @PostMapping(value = "list")
    public CommonResult list(@RequestBody JmxScriptVO vo) {
        IPage<JmxScript> page = new Page<>(vo.getCurrentPage(), vo.getPageSize());
        Wrapper<JmxScript> wrapper = Wrappers.query();
        if(StringUtils.isNotBlank(vo.getCondition())) {
           wrapper = Wrappers.<JmxScript>lambdaQuery()
                    .like(JmxScript::getId, vo.condition)
                    .or().like(JmxScript::getScriptName, vo.condition)
                    .or().like(JmxScript::getCreateBy, vo.condition);
        }
        IPage<JmxScript> data = scriptService.page(page, wrapper);
        log.info("{}", data.toString());
        return CommonResult.success(data);
    }


    @PostMapping("save")
    public CommonResult save(@RequestPart("file") MultipartFile file, @RequestPart("script") JmxScript script) throws IOException {
        scriptService.addOrEditJmxScript(file, script);
        return CommonResult.success();
    }

    @GetMapping("delete/{id}")
    public CommonResult delete(@PathVariable("id") int id) {
        scriptService.removeById(id);
        FileUtil.del(new File(Constant.JMX_FILE_SERVER_DIR + "/" + id));
        return CommonResult.success();
    }

    @GetMapping("arguments/{id}")
    public CommonResult arguments(@PathVariable("id") int id) throws Exception {
        return CommonResult.success(scriptService.getArguments(id));
    }

    @PostMapping("updateArgument")
    public CommonResult updateArguments(@RequestBody JmxArguments arguments) throws Exception {
        scriptService.updateArgument(arguments);
        return CommonResult.success();
    }

    @GetMapping("tetInitJmx/{id}")
    public CommonResult tetInitJmx(@PathVariable("id") int id) throws Exception {
        scriptService.initThreadGroup1(scriptService.getById(id));
        return CommonResult.success();
    }
}
